# xxxx - someday "pickle" this information so it isn't
#  recomputed for every access...
import os

raise ImportError, "this is historical, don't use this module"

class Sectionizer:
    """
    Look for using organization between files with naming convention:
       PrefixN_N_N_N.descriptiveName.whiff
    for example if prefix is "X" then
       X.intro.whiff is start document
       X10.tutorial.whiff is a top level entry
       X10_20.installing.whiff is a member of the tutorial
       X10_30.deleting.whiff is a later member of the tutorial.
    """
    def __init__(self, directory, prefix, suffix="whiff"):
        self.prefix = prefix
        self.suffix = suffix
        self.directory = directory
        self.filenameToLocator = {}
        self.locatorToFilename = {}
        filenames = os.listdir(directory)
        #pr "in directory", directory
        #pr "checking", filenames
        for filename in filenames:
            #pr "checking", filename
            test = fileNameTuple(filename, prefix, suffix)
            if test:
                #pr "found", test
                (locator, descriptive) = test
                self.filenameToLocator[filename] = locator
                self.locatorToFilename[locator] = filename
        fd = self.fileDictionaries = {}
        lf = self.locatorToFilename.items()
        for (locator, filename) in lf:
            fd[locator] = {"filename": filename, "children": []}
        # raises KeyError if any children are orphans
        for (locator, filename) in lf:
            if locator:
                parentLocator = locator[:-1]
                fd[parentLocator]["children"].append(locator)
                
    def getTemplateInfos(self, env):
        import getSectionPosition
        sds = self.locatorToTemplateInfo = {}
        directory = env["directory"]
        for (locator, filename) in self.locatorToFilename.items():
            sds[locator] = getSectionPosition.templateInfo(directory, filename)

    def assignJsNames(self, env):
        from whiff import gateway
        ld = self.fileDictionaries.items()
        ld.sort() # for determinism
        divResource = ["freshName", "divId"] 
        expResource = ["freshName", "expand"] 
        colResource = ["freshName", "collapse"] 
        for (locator, d) in ld:
            d["divId"] = gateway.getResource(env, divResource)
            d["colFn"] = gateway.getResource(env, colResource)
            d["expFn"] = gateway.getResource(env, expResource)

    def markFocusedFiles(self, filename):
        locator = self.filenameToLocator[filename]
        self.fileDictionaries[locator]["focus"] = True
        while locator:
            locator = locator[:-1]
            self.fileDictionaries[locator]["focus"] = True
        
    def fileInfo(self, filename, withRelations=True):
        return FileInfo(filename, self, withRelations)

class FileInfo:
    """
    encapsulate file information
    """
    def __init__(self, filename, sectionizer, withRelations):
        # sequence of filenames for ancestors
        self.prefix = sectionizer.prefix
        self.filename = filename
        self.ancestors = []
        self.previous = self.next = None
        self.children = []
        allLocators = sectionizer.locatorToFilename.items()
        allLocators.sort()
        myL = self.myLocator = sectionizer.filenameToLocator.get(filename)
        #pr "found locator", myL, "for", filename
        myLn = 0
        if myL:
            myLn = len(myL)
        seen = False
        lastchildlocator = None
        for (locator, filename) in allLocators:
            #pr "checking locator", locator, "for", filename, "against", myL
            if locator!=myL and isTuplePrefix(locator, myL):
                #pr "ancestor"
                self.ancestors.append(filename)
            elif isTuplePrefix(myL, locator):
                #pr "prefix!"
                if myL==locator:
                    #pr "same"
                    seen = True
                if len(locator)==myLn+1:
                    #pr "child"
                    self.children.append(filename)
                    lastchildlocator = locator
            else:
                if seen:
                    if self.next is None:
                        self.next = filename
                else:
                    self.previous = filename
        # finally hypothesize a position for the next child
        if lastchildlocator:
            prefix = lastchildlocator[:-1]
            lastposition = lastchildlocator[-1]
            #pr "GOT LASTPOSITION", lastposition
            lastint = int(lastposition)
            nextint = lastint + 100
            nextchildlocator = ("XXXXX",)
            if prefix is not None:
                nextchildlocator = tuple(prefix) + (str(nextint),)
        else:
            nextchildlocator = ("XXXXX",)
            if myL is not None:
                nextchildlocator = tuple(myL)+("1000",)
        self.nextChild = tupleFileName(nextchildlocator, self.prefix)

def isTuplePrefix(tuplePrefix, otherTuple):
    if tuplePrefix is None:
        return False
    ltp = len(tuplePrefix)
    if otherTuple is None or ltp>len(otherTuple):
        #pr (tuplePrefix, otherTuple), "not prefix, too long"
        return False
    truncTuple = otherTuple[:ltp]
    if truncTuple==tuplePrefix:
        return True
    return False

def tupleFileName(locator, prefix, suffix="whiff"):
    strs = [str(x) for x in locator]
    slocator = "_".join(strs)
    fs = [slocator, "DESCRIPTION", suffix]
    filename = prefix + ".".join(fs)
    return filename

def fileNameTuple(filename, prefix, suffix="whiff"):
    """
    for PrefixN_N_N_N.descriptiveName.whiff
    return ( (N,N,N,N), descriptiveName )
    or None on parse failure.
    """
    #pr "filenameTuple", (filename, prefix, suffix)
    if not filename.startswith(prefix):
        #pr "no prefix", (prefix, filename)
        return None
    filename = filename[ len(prefix): ]
    fs = filename.split(".")
    if len(fs)!=3:
        #pr "bad dot split", fs
        return None
    [locator, descriptiveName, suff] = fs
    if suff!=suffix:
        #pr "bad suffix", suff
        return None
    if not locator:
        locatorTuple = ()
    else:
        locatorTuple = tuple(locator.split("_"))
    return (locatorTuple, descriptiveName)
